package com.hoshiicloud.user.service.impl.store;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.user.entity.platform.Platform;
import com.hoshiicloud.user.entity.store.PlatStore;
import com.hoshiicloud.user.feign.GoodsService;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.store.PlatStoreMapper;
import com.hoshiicloud.user.param.PlatStoreQueryParam;
import com.hoshiicloud.user.service.platform.PlatformService;
import com.hoshiicloud.user.service.store.PlatStoreService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 平台店铺 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-05-21
 */
@Slf4j
@Service
public class PlatStoreServiceImpl extends ServiceImpl<PlatStoreMapper, PlatStore> implements PlatStoreService {

    @Autowired
    private PlatformService platformService;

    @Autowired
    private IdGeneratorService idGeneratorService;

    @Autowired
    private PlatStoreMapper platStoreMapper;

    @Autowired
    private GoodsService goodsService;

    @Override
    @Logable(authName = "店铺管理-平台店铺管理-分页查询平台店铺")
    @Cacheable(cacheNames = "PlatStore",key ="#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public Page<PlatStore> getPage(Page<PlatStore> page, QueryWrapper<PlatStore> queryWrapper,String key) {
        baseMapper.selectPage(page, queryWrapper);
        return page;
    }

    /**
     * @param id
     * @return com.hoshiicloud.store.entity.PlatStore
     * @description: 根据id查询平台店铺
     */
    @Override
    @Cacheable(cacheNames = "PlatStore", key = "#root.targetClass.simpleName + ':' + #root.methodName + ':' + #id")
    @Logable(authName = "店铺管理-平台店铺 -查询平台店铺 ")
    public PlatStore getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @return boolean
     * @description: 新增平台店铺
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "PlatStore", allEntries = true)
    @Logable(authName = "店铺管理-平台店铺-新增平台店铺")
    public boolean save(PlatStore entity){

        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        Platform response = platformService.getById(entity.getPlatId());
        if (null == response) {
            throw new ServiceException(CommonError.error("新增失败，没有找到平台信息"));
        }
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @return boolean
     * @description: 修改平台店铺
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "PlatStore", allEntries = true)
    @Logable(authName = "店铺管理-平台店铺管理-修改平台店铺")
    public boolean updateById(PlatStore entity) {
        entity.setModifiedTime(LocalDateTime.now());
        Platform response = platformService.getById(entity.getPlatId());
        if (null == response) {
            throw new ServiceException(CommonError.error("修改失败，没有找到平台信息"));
        }
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "PlatStore", allEntries = true)
    @Logable(authName = "店铺管理-平台店铺管理-删除平台店铺")
    public boolean deletePlatStoreById(Long id) {
        PlatStore entity = this.getById(id);
        if(entity==null){
            throw new ServiceException(CommonError.error("删除平台店铺异常，无法找到平台店铺记录"));
        }
        entity.setModifiedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }
    @Override
    @Cacheable(cacheNames = "PlatStore", key = "#root.targetClass.simpleName + ':' + #root.methodName + ':' + #key")
    @Logable(authName = "店铺管理-平台店铺管理-根据id集合查询平台店铺")
    public List<PlatStore> getByIds(List<Long> ids, String key) {
        return  baseMapper.selectBatchIds(ids);
    }

    /**
     * 根据平台ID获取店铺列表
     * @param platId 平台ID
     * @return List<PlatStore>
     */
    @Cacheable(cacheNames = "PlatStore", key = "#root.targetClass.simpleName + ':' + #root.methodName + ':' + #platId")
    @Logable(authName = "店铺管理-平台店铺管理-根据平台ID获取店铺列表")
    @Override
    public List<PlatStore> getStoresByPlatId(Long platId) {
        QueryWrapper<PlatStore> queryWrapper = new QueryWrapper<>();
        if (null != platId) {
            queryWrapper.eq("plat_id",platId);
        }
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 批量更新店铺信息
     * @param stores 店铺列表
     * @return List<Long>
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "PlatStore", allEntries = true)
    @Logable(authName = "店铺管理-平台店铺管理-批量更新店铺信息")
    @Override
    public List<Long> batchUpdateStores(List<PlatStore> stores) {
        List<Long> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(stores)) {
            stores.forEach(item -> {
                int row = baseMapper.updateById(item);
                if (row <= 0) {
                    throw new ServiceException(CommonError.error("修改失败!"));
                } else {
                    result.add(item.getId());
                }
            });
        }
        return result;
    }

    /**
     * 查询店铺列表（带距离）
     * @param param 查询参数
     * @return IPage<Map<String, Object>>
     */
    @Logable(authName = "店铺管理-平台店铺管理-查询店铺列表（带距离）")
    @Cacheable(cacheNames = "PlatStore",key ="#root.targetClass.simpleName+':'+#root.methodName+':'+#param.getPlatId()+':'+#param.getLongitude()+':'+#param.getLatitude()+':'+#param.getPageNumber()+':'+#param.getPageSize()")
    @Override
    public IPage<Map<String, Object>> storeRange(PlatStoreQueryParam param) {
        IPage<Map<String, Object>> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
        BigDecimal longitude = param.getLongitude();
        BigDecimal latitude = param.getLatitude();
        return platStoreMapper.getListByRange(page, longitude, latitude, param.getPlatId());
    }


    @Override
    @Logable(authName = "店铺管理-平台店铺管理-根据总店ID 查询")
    @Cacheable(cacheNames = "PlatStore",key ="#root.targetClass.simpleName+':'+#root.methodName+':'+#storeId")
    public List<PlatStore> listByParentId(Long storeId) {
        QueryWrapper<PlatStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PlatStore::getParentId,storeId).eq(PlatStore::getDeleted,0);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 新增店铺
     * @param stores
     * @return
     * @throws ServiceException
     */
    @Override
    public Long insert(PlatStore stores){
        stores.setCreatedTime(LocalDateTime.now());
        stores.setModifiedTime(LocalDateTime.now());
        stores.setCreatedBy("admin");
        stores.setModifiedBy("admin");
        int row = baseMapper.insert(stores);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增店铺失败"));
        }
        return stores.getId();
    }


}

